<?php
namespace app\admin\controller;

use think\facade\View;
use app\common\business\Category as categoryBusi;
class Category extends AdminBase
{
	public function index(){
		$pid = input('param.pid',0,'intval');
		$data = [
			'pid' => $pid,
		];
		try{
			$categorys = (new categoryBusi())->getLists($data,5);
		}catch(\Exception $e){
			$categorys = [];
		}
		//halt($categorys);
		// return View::fetch();
		return View::fetch("",[
			'categorys' => $categorys,
			'pid' => $pid,
		]);
		
	}

	public function add(){
		$res = (new categoryBusi())->getNormalCategorys();
		//halt($res);
		return View::fetch("",[
			'categorys' => json_encode($res),
		]);
	}

	// 添加分类
	public function save(){
		$pid = input("param.pid",0,"intval");
		$name = input("param.name","","trim");

		//参数校验
		$data = [
			'pid' => $pid,
			'name' => $name,
		];
		//print_r($data);
		$validate = new \app\admin\validate\Category();
		if(!$validate->check($data)){
			return show(config('status.error'),$validate->getError());
		}

		try{
			$result = (new categoryBusi())->add($data);
			// var_dump($result);
		}catch(\Exception $e){
			return show(config('status.error'),$e->getMessage());
		}
		if($result){
			return show(config('status.success'),"ok");
		}
		return show(config('status.error'),"添加分类失败");    
		
	}

	// 排序
	public function listorder(){
		$id = input("param.id",0,"intval");
		$listorder = input("param.listorder",0,"intval");
		if(!$id){
			return show(config('status.error'),'参数错误');
		}
		try{
			$res = (new categoryBusi())->listorder($id,$listorder);
		}catch(\Exception $e){
			return show(config('status.error'),$e->getMessage());
		}
		if($res){
			return show(config('status.success'),"排序成功");
		}
		return show(config('status.error'),"排序失败");
	}

	// 状态 更改
	public function status(){
		$id = input("param.id",0,"intval");
		$status = input("param.status",0,"intval");
		// validate校验 

		if(!$id || !in_array($status, [0,1,99])){
			return show(config('status.error'),'参数错误');
		}

		try{
			$res = (new categoryBusi())->status($id,$status);
		}catch(\Exception $e){
			return show(config('status.error'),$e->getMessage());
		}

		if($res){
			return show(config('status.success'),'状态更新成功');
		}
		return show(config('status.error'),'状态更新失败');
	}

	public function dialog(){
		// 获取正常一级分类
		$categorys = (new categoryBusi())->getNormalByPid();

		return view("",[
			"categorys" => json_encode($categorys),
		]);
	}

	public function getByPid(){
		$pid = input('param.pid',0,'intval');
		$categorys = (new categoryBusi())->getNormalByPid($pid);

		return show(config('status.success'),'ok',$categorys);
	}
}